<?php

declare(strict_types=1);

namespace app\controller\admin;

use think\Request;
use app\eslib\EsUtils;
use app\model\esxsys\SmsCaptchaModel;
use app\model\admin\LoginState;
use app\model\admin\MobileModel;
use app\model\UsrUserModel;

class Sms
{
    // 注册或登录
    const EVENT_OF_LOGIN_OR_REGIST = 'login2regist';
    // 注册
    const EVENT_OF_REGIST = 'regist';
    // 更改手机号
    const EVENT_OF_CHANGE_MOBILE = 'changemobile';
    // 更改密码
    const EVENT_OF_CHANGE_PASSWORD = 'changepwd';
    // 重置密码
    const EVENT_OF_RESET_PASSWORD = 'resetpwd';
    // 短信测试验证码（超级验证码）
    const TEST_CAPTCHA = '0609';
    /**
     * 发送验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     */
    public function send(Request $request)
    {
        $userId = LoginState::getId();
        // 表单校验（alphaDash: 字母和数字，下划线_及破折号-）
        $validate = \think\facade\Validate::rule([
            'mobile'  => 'require|mobile',
            'event' => 'require|alphaDash',
        ]);
        $isDebug = $request->param('is_debug/d', 0);
        $postData = $request->param(['mobile', 'event']);
        if (!$validate->check($postData)) {
            return json(EsUtils::stdMessage(false, $validate->getError()));
        }
        extract($postData);
        // 判断是否需要登录
        if ($event != self::EVENT_OF_REGIST && $event != self::EVENT_OF_LOGIN_OR_REGIST && !$userId) {
            return json(EsUtils::stdMessage(false, '您未登录'));
        }

        $ip = $request->ip();
        if (!$isDebug) {
            // 检测安全限制
            $msgInfo = EsxdmSysSmsCaptchaModel::checkSafeLimit($mobile, $event, $ip);
            if (!$msgInfo['success']) {
                return json($msgInfo);
            }
        }
        // 创建数据库记录
        $smsModel = EsxdmSysSmsCaptchaModel::createRecord($userId, $mobile, $event, $ip);
        // 事件处理
        $userExists = UsrUserModel::where('mobile', $mobile)->count() > 0;
        switch ($event) {
            case self::EVENT_OF_REGIST:
                if ($userExists) {
                    return json(EsUtils::stdMessage(false, '手机号已被注册'));
                }
                break;
            case self::EVENT_OF_CHANGE_MOBILE:
                if ($userExists) {
                    return json(EsUtils::stdMessage(false, '手机号已被使用'));
                }
                break;
            default:
                break;
        }
        if ($isDebug) {
            $msgInfo = EsUtils::stdMessage(true, '发送成功', '[调试模式] ' . $smsModel->code);
        } else {
            $msgInfo = (new MobileModel)->sendSms($mobile, $smsModel->code);
        }
        $msgInfo['data'] = ['exists' => $userExists];
        return json($msgInfo);
    }

    /**
     * 检测验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件名称
     * @param string $captcha 验证码
     */
    public function check(Request $request)
    {
        // 接收表单数据
        $postData = $request->param(['mobile', 'event', 'captcha']);

        // 表单校验（alphaDash: 字母和数字，下划线_及破折号-）
        $validate = \think\facade\Validate::rule([
            'mobile|手机号' => 'require|mobile',
            'event|事件名称' => 'require|max:50',
            'captcha|验证码' => 'require|max:6',
        ]);
        if (!$validate->check($postData)) {
            return json(EsUtils::stdMessage(false, $validate->getError()));
        }
        $mobile = $postData['mobile'];
        $event = $postData['event'];
        $captcha = $postData['captcha'];

        $userExists = UsrUserModel::where('mobile', $mobile)->count() > 0;
        switch ($event) {
            case self::EVENT_OF_REGIST:
                if ($userExists) {
                    return json(EsUtils::stdMessage(false, '已被注册'));
                }
                break;
            case self::EVENT_OF_CHANGE_MOBILE:
                if ($userExists) {
                    return json(EsUtils::stdMessage(false, '已被占用'));
                }
                break;
            case self::EVENT_OF_CHANGE_PASSWORD:
            case self::EVENT_OF_RESET_PASSWORD:
                if (!$userExists) {
                    return json(EsUtils::stdMessage(false, '该号码未注册'));
                }
                break;
            default:
                break;
        }
        $msgInfo = EsxdmSysSmsCaptchaModel::checkCodeByMobile($mobile, $event, $captcha);
        $msgInfo['data'] = ['exists' => $userExists];
        return json($msgInfo);
    }
}
